import os
import json
import difflib
from datetime import datetime, timedelta
from modules.sigalarm.utils import EventType, Event, EventQueue, NetSpider, TimeKV


class Sig(object):

    def __init__(self, name, etherpad, contacts, contacts_group, workpath):
        self.name = name
        self.etherpad = etherpad
        self.contacts = contacts
        self.contacts_group = contacts_group

        self._last_content = os.path.join(workpath, f'{self.name}.last.content')
        self._info = os.path.join(workpath, f'{self.name}.last.info')

        self.last_detect_time = {"meeting": "1997-01-11 00:00:00", "etherpad": "1997-01-11 00:00:00"}
        self.content_last = ''
        self.content_change_time_last = ''
        self.meeting_last = ''
        self.meeting_time_last = ''

    def begin(self):
        if not os.access(self._last_content, os.F_OK):
            return

        with open(self._last_content, 'r', encoding='utf-8') as f:
            lines = f.readlines()
        with open(self._info, 'r', encoding='utf-8') as f:
            info = json.load(f)

        self.last_detect_time = info["last_detect_time"]
        self.content_last = ''.join(lines)
        self.content_change_time_last = info['content_change_time_last']
        self.meeting_last = info['meeting_last']
        self.meeting_time_last = info['meeting_time_last']

    def end(self):
        with open(self._last_content, 'w', encoding='utf-8') as f:
            f.write(self.content_last)
        with open(self._info, 'w', encoding='utf-8') as f:
            info = {
                "last_detect_time": self.last_detect_time,
                "content_change_time_last": self.content_change_time_last,
                "meeting_last": self.meeting_last,
                "meeting_time_last": self.meeting_time_last
            }
            json.dump(info, f)

    def detect_etherpad(self):
        now = datetime.now()
        last_detect_time = self.last_detect_time["etherpad"]
        if now - datetime.strptime(last_detect_time, '%Y-%m-%d %H:%M:%S') < timedelta(hours=2):
            return

        last_detect_time = now.strftime('%Y-%m-%d %H:%M:%S')
        now = now.strftime('%Y-%m-%d %H:%M')
        content_last = TimeKV(self.content_change_time_last, self.content_last)
        content_now = TimeKV(now, NetSpider.get_text('{}/export/txt'.format(self.etherpad)))
        if content_now.val is None:
            EventQueue.put(Event(EventType.ETHERPAD_DOWNLOAD_ERR, self, now, ''))
            return

        self.last_detect_time["etherpad"] = last_detect_time
        self.content_last = content_now.val

        if content_last.val is None or content_last.val == '':
            self.content_change_time_last = content_now.time_str
            EventQueue.put(Event(EventType.SIG_FIRST_INIT, self, now, ''))
            return

        if content_last.val == content_now.val:
            EventQueue.put(Event(EventType.ETHERPAD_NOTHING_CHANGED, self, now, ''))
            return

        self.content_change_time_last = content_now.time_str
        diff = difflib.unified_diff(
            content_last.val.splitlines(),
            content_now.val.splitlines(),
            lineterm='',
            fromfile=content_last.time_str,
            tofile=content_now.time_str)
        EventQueue.put(Event(EventType.ETHERPAD_CHANGED, self, now, '\n'.join(diff)))

    def detect_meeting(self):
        last_detect_time = self.last_detect_time["meeting"]
        now = datetime.now()
        if now - datetime.strptime(last_detect_time, '%Y-%m-%d %H:%M:%S') < timedelta(minutes=5):
            return

        meeting_last = TimeKV(self.meeting_time_last, self.meeting_last)
        if meeting_last.time_val < now:
            self.meeting_time_last = ''
            self.meeting_last = ''
            meeting_last = TimeKV(self.meeting_time_last, self.meeting_last)

        url = f"https://opengauss.org/api-meeting/meetingsdata/?group={self.name}"
        data = NetSpider.get_json(url)
        self.last_detect_time["meeting"] = now.strftime('%Y-%m-%d %H:%M:%S')
        for day_schedule in data["tableData"]:
            for cell in day_schedule["timeData"]:
                meeting = TimeKV(f'{day_schedule["date"]} {cell["startTime"]}', cell["join_url"])
                if meeting.time_val < now:
                    continue

                if meeting.val != meeting_last.val or meeting.time_str != meeting_last.time_str:
                    EventQueue.put(Event(EventType.MEETING_NEW, self, now, meeting.val))
                    self.meeting_last = meeting.val
                    self.meeting_time_last = meeting.time_str

                if timedelta() < meeting.time_val - now <= timedelta(minutes=5):
                    EventQueue.put(Event(EventType.MEETING_ALARM, self, now, meeting.val))

                return

        EventQueue.put(Event(EventType.MEETING_NOTHING_CHANGED, self, now, ''))
